package com.wang.util;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;

import javax.sql.DataSource;

import org.apache.commons.dbcp.BasicDataSourceFactory;

public class DBCPUtil {
	static DataSource createDataSource;
	static {
		Properties properties = new Properties();
		properties.setProperty("url", "jdbc:mysql:///homework?createDatabaseIfNotExist=true");
		properties.setProperty("username", "root");
		properties.setProperty("password", "123123");
		properties.setProperty("driverClassName", "com.mysql.jdbc.Driver");
		try {
			createDataSource = BasicDataSourceFactory.createDataSource(properties);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	public static Connection getConnection() throws SQLException{
		return createDataSource.getConnection();
	}
	public static void close(ResultSet rs,Statement ps,Connection c){
		try {
			if(rs != null)
				rs.close();
		} catch (SQLException e) {
			e.printStackTrace();
		} finally{
			try {
				if(ps != null)
					ps.close();
			} catch (SQLException e) {
				e.printStackTrace();
			} finally{
				try {
					if(c != null)
						c.close();
				} catch (SQLException e) {
					e.printStackTrace();
				}
			}
		}
	}
}
